import React, { useEffect, useState } from 'react';
import { isEmpty } from 'lodash';

import {
  platform,
  downplatform,
  downstatsList,
} from '@/services/videoImagesSupport';
import Split from '@/components/Split';
import BasicPlatform from './BasicPlatform';
import SubPlatform from './SubPlatform';

const VideoCloudPortal = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [downstatsListData, setDownstatsListData] = useState<any[]>([]);
  const [platformData, setPlatformData] = useState<any>({});
  const [downplatformData, setDownplatformData] = useState<any>({});

  // handleQuery
  const handleQuery = async () => {
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };
  // 获取平台数据
  const query = async () => {
    const queryPlatform = platform();
    const queryDownstatsList = downstatsList();
    // 先获取下级
    const queryDownstatsListRes = await queryDownstatsList;
    try {
      const downstatsListdata = queryDownstatsListRes.data.data;
      setDownstatsListData(downstatsListdata);
      if (!isEmpty(downstatsListdata)) {
        const initDownstatsName = downstatsListdata[0].name;
        const queryDownPlatform = downplatform({
          downstats: initDownstatsName,
        });

        Promise.all([queryPlatform, queryDownPlatform]).then(res => {
          const [queryPlatformRes, queryDownPlatformRes] = res;
          setPlatformData(queryPlatformRes.data.data);
          setDownplatformData(queryDownPlatformRes.data.data);
          handleQuery();
        });
      } else {
        const queryPlatformRes = await queryPlatform;
        setPlatformData(queryPlatformRes.data.data);
        handleQuery();
      }
    } catch (error) {
      handleQuery();
      console.log(error);
    }
  };

  // 下拉选择下级平台
  const onChane = async (name: string) => {
    const queryDownPlatformRes = await downplatform({ downstats: name });
    setDownplatformData(queryDownPlatformRes.data.data);
  };

  const SubPlatformProps = {
    loading,
    downstatsList: downstatsListData,
    data: downplatformData,
    onChangeDownstats: onChane,
  };

  useEffect(() => {
    query();
  }, []);
  return (
    <>
      <BasicPlatform loading={loading} data={platformData} />
      <Split />
      <SubPlatform {...SubPlatformProps} />
    </>
  );
};

export default VideoCloudPortal;
